<template>
  <!--  查询 -->
  <div>
    <el-input placeholder="请输入客户ID" style="width:200px" v-model="queryId"></el-input>
    <el-button @click="queryById" type="success" plain>查询</el-button>
    <el-button @click="showCustomerDialog" type="primary" style="width: 100px; margin-left: 50px;font-weight: bolder; font-size: 16px">
      登&emsp;记
    </el-button>
  </div>
  <!--  显示所有客户信息 table自动循环-->
  <div>{{errorMessage}}</div>
  <el-table :data="customerList">
    <el-table-column label="序号" type="index" width="60px"></el-table-column>
    <el-table-column prop="customerId" label="客户ID" width="70px"></el-table-column>
    <el-table-column prop="remarks" label="备注" width="70px"></el-table-column>
    <el-table-column prop="outgoingreason" label="外出事由" width="80px"></el-table-column>
    <el-table-column prop="outgoingtime" label="外出时间" width="100px" :formatter="formatDate"></el-table-column>
    <el-table-column prop="expectedreturntime" label="预计回院时间" width="110px" :formatter="formatDate"></el-table-column>
    <el-table-column prop="actualreturntime" label="实际回院时间" width="110px" :formatter="formatDate"></el-table-column>
    <el-table-column prop="escorted" label="陪同人" width="80px"></el-table-column>
    <el-table-column prop="relation" label="与老人关系" width="100px"></el-table-column>
    <el-table-column prop="escortedtel" label="陪同人电话" width="100px"></el-table-column>
    <el-table-column prop="auditstatus" label="审批状态" width="80px">
      <template #default="scope">
        {{scope.row.auditstatus === 0? '已提交' : (scope.row.auditstatus === 1? '同意' : (scope.row.auditstatus === 2? '拒绝' : ''))}}
      </template>
    </el-table-column>
    <el-table-column prop="auditperson" label="审批人" width="80px"></el-table-column>
    <el-table-column prop="audittime" label="审批时间" width="110px" :formatter="formatDate"></el-table-column>
    <el-table-column  label="操作">
      <template #default="scope">
        <el-button type="primary" @click="showEditDialog(scope.row.id)">修改</el-button>
        <el-button type="success" @click="markAsReturned(scope.row.id)">回归</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="example-pagination-block">
    <el-pagination background
                   v-model:current-page="pageContains.pageNum"
                   v-model:page-size="pageContains.pageSize"
                   :page-sizes="[10,20,30,50,100]"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="pageContains.total"
                   @size-change="handleSizeChange"
                   @current-change="handlePageChange"
    />
  </div>

  <!--  客户信息对话框 -->
  <el-dialog v-model="customerDialog" :title="dialogTitle">
    <el-form :model="curCustomer">
      <el-form-item label="选择客户">
        <el-select v-model="curCustomer.customer_id" placeholder="请选择客户" filterable clearable @change="onCustomerSelect" style="width: 200px;">
          <el-option v-for="customer in availableCustomerOptions" :key="customer.id" :label="customer.customerName" :value="customer.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="客户&emsp;ID">
        <el-col :span="11">
          <el-input v-model="curCustomer.customerId" disabled></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="备&emsp;&emsp;注">
        <el-col :span="11">
          <el-input v-model="curCustomer.remarks"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="外出事由">
        <el-col :span="11">
          <el-input v-model="curCustomer.outgoingreason"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="外出时间">
        <el-col :span="11">
          <el-date-picker v-model="curCustomer.outgoingtime"></el-date-picker>
        </el-col>
      </el-form-item>
      <el-form-item label="预计回院时间">
        <el-col :span="11">
          <el-date-picker v-model="curCustomer.expectedreturntime"></el-date-picker>
        </el-col>
      </el-form-item>
      <el-form-item label="实际回院时间">
        <el-col :span="11">
          <el-date-picker v-model="curCustomer.actualreturntime"></el-date-picker>
        </el-col>
      </el-form-item>
      <el-form-item label="陪同人">
        <el-col :span="11">
          <el-input v-model="curCustomer.escorted"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="与老人关系">
        <el-col :span="11">
          <el-input v-model="curCustomer.relation"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="陪同人电话">
        <el-col :span="11">
          <el-input v-model="curCustomer.escortedtel"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="审批状态">
        <el-col :span="11">
          <el-select v-model="curCustomer.auditstatus">
            <el-option
                v-for="item in statusOptions"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-form-item>

      <el-form-item label="审批人：">
        <el-col :span="11">
          <el-input v-model="curCustomer.auditperson"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="审批时间">
        <el-col :span="11">
          <el-date-picker v-model="curCustomer.audittime"></el-date-picker>
        </el-col>
      </el-form-item>
    </el-form>
    <el-button @click="optOne()">{{buttonOpt}}</el-button>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import http from '@/axios/http';
import qs from "qs";
import { ElMessage } from 'element-plus';

// 存放用户数据集合
let customerList = ref([]);

// 报错提示
let errorMessage = ref("")

// 模糊查询绑定的 客户ID
let queryId = ref("")

// 对话框显示控制
let customerDialog = ref(false)

// 客户信息，或者编辑已有客户的 绑定数据
let curCustomer = ref({
  customer_id: null
});

// 登记、修改客户信息弹出框的 标题和操作按钮  显示文字
let dialogTitle = reactive("")
let buttonOpt = reactive("")

// 对话框操作类型：1：添加 2：编辑
let dialogOptType = reactive(1)
let size = 10; // 当前显示多少行
let pageNum = 1; // 当前页码
let pageSize = 10; // 每页显示行数

// 当前页码信息
let pageContains = ref({})

// 审批数组
let statusOptions = ref([
  {
    label: '已提交',
    value: 0
  },
  {
    label: '同意',
    value: 1
  },
  {
    label: '拒绝',
    value: 2
  }
])

const customerOptions = ref([]);
const availableCustomerOptions = ref([]);

// 标识客户是否正在外出（有未回归的外出记录）
let isCustomerOutwarding = ref(false);

// 获取客户列表（用于选择）
async function getCustomerOptions() {
  try {
    const res = await http.get('/lyy/get_Customer_List');
    if (res.data.result ==='success') {
      customerOptions.value = res.data.data.map(customer => ({
        id: customer.id,
        customerName: customer.customerName,
        customerId: customer.id
      }));
      await updateAvailableCustomerOptions();
    } else {
      ElMessage.error('获取客户列表失败：' + res.data.error);
    }
  } catch (error) {
    console.error('请求后端接口失败：', error);
    ElMessage.error('请求后端接口失败，请稍后重试');
  }
}

// 更新可用客户选择列表
async function updateAvailableCustomerOptions() {
  const availableCustomers = [];
  for (const customer of customerOptions.value) {
    const hasUnreturned = await checkCustomerOutwardStatus(customer.id);
    if (!hasUnreturned) {
      availableCustomers.push(customer);
    }
  }
  availableCustomerOptions.value = availableCustomers;
}

// 当选择客户时触发
async function onCustomerSelect(customerId) {
  const selectedCustomer = customerOptions.value.find(customer => customer.id === customerId);
  if (selectedCustomer) {
    curCustomer.value.customerId = selectedCustomer.customerId;
    // 检查客户是否正在外出
    const hasUnreturned = await checkCustomerOutwardStatus(customerId);
    isCustomerOutwarding.value = hasUnreturned;
    if (hasUnreturned) {
      ElMessage.warning('该客户已办理外出登记且未回归，不能再次录入');
      curCustomer.value.customer_id = null; // 清空已选客户
      curCustomer.value.customerId = '';
    }
  }
}

// 检查客户是否正在外出
async function checkCustomerOutwardStatus(customerId) {
  try {
    const res = await http.post('/lyy/check_customer_outward_status', { customerId });
    if (res.data.result ==='success') {
      return res.data.data;
    } else {
      throw new Error(res.data.error);
    }
  } catch (error) {
    console.error('请求后端接口失败：', error);
    throw error;
  }
}

// 根据客户ID模糊查询客户信息
function queryById() {
  let param = {
    customerId: queryId.value
  }
  http.post('/lyy/get_outwards_by', param).then(
      (res) => {
        let result = res.data;
        // 返回结果传给 customerList
        if (result.result ==='success') {
          customerList.value = result.data;
        } else {
          errorMessage.value = result.error;
        }
      }
  )
}

// 单击登录按钮事件
async function showCustomerDialog() {
  await updateAvailableCustomerOptions();
  dialogTitle = "外出信息登记";
  buttonOpt = "录入";
  // 弹出客户信息对话框
  customerDialog.value = true;
  dialogOptType = 1; // 设置当前操作类型标志是 录入
  curCustomer.value.customer_id = null;
  curCustomer.value.customerId = '';
  isCustomerOutwarding.value = false;
}

// 关闭客户信息对话框
function closeCustomerDialog() {
  customerDialog.value = false;
}

// 页面初始化
onMounted(async () => {
  await init();
  await getCustomerOptions();
})

async function init() {
  // 查询所有用户信息
  await getAllCustomers();
  // 查询需要的字典（{标志1: 值1, 标志2: 值2}）
  // 用的时候取 字典[字段值（字典标志）]
}

function getAllCustomers() {
  let params = {
    size: size,
    pageNum: pageNum,
    pageSize: pageSize
  }
  http.post('/lyy/get_all_outward', params).then(
      (res) => {
        let result = res.data;
        // 返回结果传给 customerList
        if (result.result ==='success') {
          pageContains.value = result.data;
          // pageContains.list = null;
          customerList.value = result.data.list;
        } else {
          errorMessage.value = result.error;
        }
      }
  )
}

// 格式化日期
function formatDate(row, column) {
  let data = row[column.property];
  if (data == null) {
    return null;
  }
  let dt = new Date(data);
  return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate();
  // + ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()
}

function recordOne() {
  if (isCustomerOutwarding.value) {
    ElMessage.warning('该客户已办理外出登记且未回归，不能再次录入');
    return;
  }
  let param = curCustomer.value;
  http.post('/lyy/add_one_outward', param).then(
      (res) => {
        let result = res.data;
        // 返回结果传给 customerList
        if (result.result ==='success') {
          // 从可用客户列表中移除已选择的客户
          const index = availableCustomerOptions.value.findIndex(customer => customer.id === curCustomer.value.customer_id);
          if (index!== -1) {
            availableCustomerOptions.value.splice(index, 1);
          }
          // 关闭对话框
          closeCustomerDialog();
          // 刷新客户列表
          getAllCustomers();
          // 更新客户外出状态
          isCustomerOutwarding.value = true;
          ElMessage.success('外出登记成功');
        } else {
          errorMessage.value = result.error;
          ElMessage.error('外出登记失败：' + result.error);
        }
      }
  )
}

// 显示编辑对话框
function showEditDialog(id) {
  // 根据id查询客户信息
  getCustomerInfo(id);
  // 显示对话框
  console.log(id);
  customerDialog.value = true;
  dialogTitle = "外出住信息修改";
  buttonOpt = "修改";
  dialogOptType = 2; // 设置当前操作类型标志是 修改
}

function getCustomerInfo(id) {
  let param = {
    id: id
  }
  http.post('/lyy/getoutward_id', qs.stringify(param)).then(
      (res) => {
        let result = res.data;
        // 返回结果传给 customerList
        if (result.result === 'success') {
          curCustomer.value = result.data;
        } else {
          errorMessage.value = result.error;
        }
      }
  )
}

// 标记为已回归
async function markAsReturned(id) {
  let param = {
    id: id,
    actualreturntime: new Date()
  }
  http.post('/lyy/mark_outward_returned', param).then(
      async (res) => {
        let result = res.data;
        if (result.result === 'success') {
          // 刷新客户列表
          await getAllCustomers();
          // 更新可用客户选择列表
          await updateAvailableCustomerOptions();
          // 更新客户外出状态
          const hasUnreturned = await checkCustomerOutwardStatus(curCustomer.value.customer_id);
          isCustomerOutwarding.value = hasUnreturned;
          ElMessage.success('客户已成功回归');
        } else {
          errorMessage.value = result.error;
          ElMessage.error('标记客户回归失败：' + result.error);
        }
      }
  )
}

function editOne() {
  let param = curCustomer.value;
  http.post('/lyy/modifyoutwardby_id', param).then(
      (res) => {
        let result = res.data;
        if (result.result === 'success') {
          // curCustomer.value = result.data;
          closeCustomerDialog();
          getAllCustomers();
        } else {
          errorMessage.value = result.error;
        }
      }
  )
}

function optOne() {
  if (dialogOptType === 1) {
    recordOne();
  } else if (dialogOptType === 2) {
    editOne();
  }
}

// 分页处理
const handlePageChange = (pageNum1) => {
  pageNum = pageNum1;
  getAllCustomers();
}

const handleSizeChange = (pageSize1) => {
  pageSize = pageSize1;
  getAllCustomers();
}
</script>

<style scoped>

</style>